<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="ctxPath" value="${pageContext.request.contextPath}"/>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <title>房间类型列表</title>
  <link rel="stylesheet" href="${ctxPath}/layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="${ctxPath}/layuiadmin/style/admin.css" media="all">
  <style>
    body{margin: 10px;}
    .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    input[readonly]{
    }
  </style>
</head>
<body>
<table class="layui-hide" id="demo" lay-filter="test"></table>
 
<script type="text/html" id="toolBar">
  <a class="layui-btn layui-btn-normal layui-btn-xs layui-btn-radius" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs layui-btn-radius" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>
<script type="text/html" id="headToolBar">
<div class="layui-btn-group">
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="add">
    <i class="layui-icon">&#xe654;</i>
  </button>
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="update">
    <i class="layui-icon">&#xe642;</i>
  </button>
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="delete">
    <i class="layui-icon">&#xe640;</i>
  </button>
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="search">
    <i class="layui-icon">&#xe615;</i>
  </button>
</div>
</script>

 <script src="${ctxPath}/layuiadmin/layui/layui.js"></script> 
<script src="${ctxPath}/js/jquery-1.11.1.min.js"></script>


<script>
var r=Math.floor(Math.random()*6);
 
layui.use(
	['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider'], 
	function(){
	  var laydate = layui.laydate //日期
	  ,laypage = layui.laypage //分页
	  ,layer = layui.layer //弹层
	  ,table = layui.table //表格
	  ,carousel = layui.carousel //轮播
	  ,upload = layui.upload //上传
	  ,element = layui.element //元素操作
	  ,slider = layui.slider //滑块
	  ,admin = layui.admin
	  ,form = layui.form;
	  
	  //layer.msg('用户列表',{icon:6,time:2000,offset:'20px'});
  
  //{ps} 监听Tab切换
  element.on('tab(demo)', function(data){
    layer.tips('切换了 '+ data.index +': '+ this.innerHTML, this, {
      tips: 1
    });
  });
  
  //{ps} 执行一个 table 实例
  var ran = Math.random();
  table.render({
    elem: '#demo'
    ,height: 'full-100'
    ,url: '${ctxPath}/RoomType/jsonList?ran='+ ran //数据接口
    ,title: '用户表'
    ,page: true     //{ps} 开启分页
    ,toolbar: '#headToolBar' //{ps} 开启工具栏，此处显示默认图标，可以自定义模板，详见文档
    ,totalRow: false //{ps} 开启合计行
    ,limit:1000
    ,limits:[10,20,50,100,200,500,1000,2000]
    ,cellMinWidth:80
    ,cols: [[
      {type: 'checkbox'},
      {field: 'id', title: 'ID', width:100, sort: true},
      {field: 'typeName', title: '类型名称', width:120,sort:true, edit:'text'},
      {field: 'dayPrice', title: '每日租价', width:120,sort:true, edit:'text'},
      {field: 'hourPrice', title: '每时租价', width:120,sort:true, edit:'text'},
      {field: 'updateDate', title: '更新日期', width:200,sort:true,hide:true},
      {field: 'createDate', title: '创建日期', width:200,sort:true},
      {fixed: 'right', title:'操作', align:'center', toolbar: '#toolBar',minWidth:150}
    ]]
    ,initSort:{
        field:'createDate',
        type:'asc',
    }
    ,text:'对不起，加载出现异常！请联系小蓝解决！'
   	,done: function(res, curr, count){
		 if (res.count == 0) {
              $(".layui-none").hide();//隐藏无数据
              $(".layui-table-page").hide();//隐藏分页
          }
	  }
  });
  
  //{ps} 监听头工具栏事件
  table.on('toolbar(test)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id)
    ,data = checkStatus.data; //获取选中的数据
    switch(obj.event){
      case 'add':
        layer.open({
            type: 2
            ,id:"onlyone"
            ,content: '${ctxPath}/RoomType/viewAddRoomType'
            ,shade:0
            ,shadeClose: false
            ,moveOut:true
            ,area: ['80%', '80%']
            ,maxmin: true
            ,anim:r
            ,title:'创建'
          });
      break;
      case 'update':
        if(data.length === 0){
        	layer.msg('请选择一行',{icon:2,time:2000,offset:'20px'});
        }  else if(data.length > 1){
        	layer.msg('只能编辑一行',{icon:2,time:2000,offset:'20px'});
        }  else {
        	/* for(var i=0;i<=(checkStatus.data).length;i++){
        		layer.alert(JSON.stringify(checkStatus.data[0]));
        	} */
           edit( checkStatus.data[0].id ); 
        }
      break;
      case 'delete':
        if(data.length === 0){
        	layer.msg('请选择一行',{icon:2,time:2000,offset:'20px'});
        } else{
        	
        	layer.confirm('删除这些房间类型吗', function(index){
        		var s='';
            	for(var i=0;i<(checkStatus.data).length;i++){
            		s=s+JSON.stringify(checkStatus.data[i]['typeName'])+",";
            		del( checkStatus.data[i].id );
        		}
            	layer.msg('删除[id]:'+s,{icon:1,time:2000,offset:'20px'});
              });
        }
      break;
      case 'search':
    	  layer.msg('按键ctrl+F,进行搜索',{icon:3,time:4000,offset:'20px'});
   	  break;
    };
  });
  
  //{ps} 监听行工具事件
  table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
    var data = obj.data     //获得当前行数据
    , layEvent = obj.event; //获得 lay-event 对应的值
    if(layEvent === 'detail'){
    	layer.msg('查看[id]:'+data.id,{icon:6,time:2000,offset:'20px'});
    } else if(layEvent === 'del'){
      	layer.confirm('删除\''+data.id+'\'房间吗', function(index){
    	layer.msg('删除[id]:'+data.id,{icon:1,time:2000,offset:'20px'});
		del( data['id'] );
      });
    } else if(layEvent === 'edit'){
    	//{1} 获取一个用户, 通过 ajax 来获取。
    	//  data['id']: 表格上面的 id 值。
		edit( data['id'] );
    }
  });
  
//监听单元格编辑
  table.on('edit(test)', function(obj){
    var value = obj.value //得到修改后的值
    ,data = obj.data //得到所在行所有键值
    ,field = obj.field; //得到字段
    $.ajax({
    			url:'${ctxPath}/RoomType/getRoomType', /* 数据接口 */
    			type:'post',
    			data:{id:data.id},
    			dataType:'json',
    			success:function( resp ){
    				if( resp['result']=='success' ){
    					var _data =resp['roomType'];
    					_data[field]=value;
    					console.log( data );
    					$.ajax({
    						url:'${ctxPath}/RoomType/saveRoomType',
    						type:'post',
    						data:_data,
    						dataType:'json',
    						success:function( resp ){
    							var result = resp['result'];
    							//{ps} 关闭弹窗
    							layer.closeAll();
    							if(result=='success'){
    								layer.msg('更新房间类型:'+ resp['typeName'] +'成功',{icon:1,time:2000,offset:'20px'});
    							}else{
    								layer.msg('更新房间类型:'+ resp['typeName'] +'失败, 原因: '+ resp['cause'],{icon:2,time:2000,offset:'20px'});
    							}
    						}
    					});
    				}else{
    					layer.msg('访问数据错误, 原因: '+ resp['cause'],{icon:2,time:2000,offset:'20px'});
    				}
    			}
    		});
  });
  
//监听行双击事件
  table.on('rowDouble(test)', function(obj){
	  edit( obj.data.id );
  });
  
});


</script>


<!-- {ps} 编写我们的 js 代码! -->
<script>
function edit( id ){
	$.ajax(
		{
			url:'${ctxPath}/RoomType/getRoomType', /* 数据接口 */
			type:'post',
			data:{id:id},
			dataType:'json',
			success:function( resp ){
				if( resp['result']=='success' ){
					console.log( resp);
					onRecvMsg( resp );   //显示对话框
				}else{
					layer.msg('访问数据错误, 原因: '+ resp['cause'],{icon:2,time:2000,offset:'20px'});
				}
			}
		}
	);
}

//{ps} 当接收到后台发来的 用户数据时，触发该方法。
//     这一个方法会传一个 json 进来。
function onRecvMsg( json ){
	var HTML="<div class=\"layui-fluid\">"+
	"<div class=\"layui-card\">"+
	"<div class=\"layui-card-header\" lay-value=\""+json['roomType']['id']+"\">"+json['roomType']['typeName']+"</div>"+
	"<div class=\"layui-card-body\" style=\"padding: 15px;\">"+
	"<form class=\"layui-form\" action=\"\" lay-filter=\"component-form-group\">"+
		"<div class=\"layui-col-md6\">"+
			"<div class=\"layui-form-item\">"+
			"<label class=\"layui-form-label\">房间类型ID</label>"+
			"<div class=\"layui-input-inline\">"+
			"<input value='"+json['roomType']['id']+"' type=\"text\" id=\"id\" name=\"id\" lay-verify=\"required\" placeholder=\""+json['roomType']['typeName']+"的ID\" autocomplete=\"off\" class=\"layui-input\" readonly>"+
			"</div>"+
			"<div class=\"layui-form-mid layui-word-aux\">只读</div>"+
			"</div>"+
		"</div>"+
		"<div class=\"layui-col-md6\">"+
			"<div class=\"layui-form-item\">"+
			"<label class=\"layui-form-label\">类型名称</label>"+
			"<div class=\"layui-input-inline\">"+
			"<input value='"+json['roomType']['typeName']+"' type=\"text\" id=\"typeName\" name=\"typeName\" lay-verify=\"required\" placeholder=\""+json['roomType']['typeName']+"的房间类型名称\" autocomplete=\"off\" class=\"layui-input\">"+
			"</div>"+
			"</div>"+
		"</div>"+
		"<div class=\"layui-col-md6\">"+
			"<div class=\"layui-form-item\">"+
			"<label class=\"layui-form-label\">日租价格</label>"+
			"<div class=\"layui-input-inline\">"+
			"<input value='"+json['roomType']['dayPrice']+"' type=\"text\" id=\"dayPrice\" name=\"dayPrice\" lay-verify=\"required\" placeholder=\""+json['roomType']['typeName']+"的日租价格\" autocomplete=\"off\" class=\"layui-input\">"+
			"</div>"+
			"</div>"+
		"</div>"+
		"<div class=\"layui-col-md6\">"+
			"<div class=\"layui-form-item\">"+
			"<label class=\"layui-form-label\">时租价格</label>"+
			"<div class=\"layui-input-inline\">"+
			"<input value='"+json['roomType']['hourPrice']+"' type=\"text\" id=\"hourPrice\" name=\"hourPrice\" lay-verify=\"required\" placeholder=\""+json['roomType']['typeName']+"的时租价格\" autocomplete=\"off\" class=\"layui-input\">"+
			"</div>"+
			"</div>"+
		"</div>"+
		"<div class=\"layui-form-item\">"+
		"</div>"+
	"</form>"+
	"</div>"+
	"</div>"+
	"</div>";
	layer.open({
         type: 1
         ,title: '编辑房间类型'      //显示标题栏
         ,closeBtn: false
         ,skin: 'layui-layer-rim'
         ,area: ['80%','80%']
         ,shadeClose: true
         ,id: 'LAY_layuipro'   //设定一个 id, 防止重复弹出
         ,btn: ['保存修改', '关闭']  //{ps} 两个按钮
         ,btnAlign: 'c'        //居中对齐
         ,moveType: 1          //拖拽模式, 0 或者 1
         ,content: HTML        //这是上面生成的表格 html 代码
         ,anim:r
         ,yes: function(){
        	   //{1} 当点击 '保存用户' 时候, 调用这个函数
               saveRoom();       //保存用户(写到数据库)
               //不建议这里关闭, 等消息回来才做。
               //layer.closeAll(); //关闭对话框
         }
         ,success: function( layero ){
        	 //重新渲染
        	 layui.use('form', function(){
                 var form = layui.form;
                 form.render();
             });
         }
	});
}    //ENDING {onRecvMsg}

//{1} 清除页面中的 maketable
//{2} 除页面中的 showBox

//{ps}你要获取的项目
var items = [
	"id", "typeName", "dayPrice", "hourPrice"
];

//{ps} 抓取表单数据
function pickData(){
	var obj = {};
	for( var i=0; i<items.length; i++ ){
		var val = $("#"+ items[i]).val().split('||')[0];
		obj[ items[i] ] = val;
		console.log(val);
	}
	return obj;
}

function saveRoom(){
	//{1}获取表单数据。
	var _data = pickData();
	console.log("Data:"+ _data );
	//(2)使用 ajax 提交数据
	$.ajax({
		url:'${ctxPath}/RoomType/saveRoomType',
		type:'post',
		data:_data,
		dataType:'json',
		success:function( resp ){
			var result = resp['result'];
			//{ps} 关闭弹窗
			layer.closeAll();
			if(result=='success'){
				layer.msg('更新房间类型：'+resp['typeName']+'成功',{icon:1,time:2000,offset:'20px'});
				//{1} 1.0秒重新刷新页面。
				setTimeout( reloadPage, 1000 );
			}else{
				layer.msg('更新房间类型:'+resp['typeName'] +'失败, 原因:'+ resp['cause'],{icon:2,time:2000,offset:'20px'});
			}
		}
	});
}

function reloadPage(){
	window.location = '${ctxPath}/RoomType/viewList';
}

function del( _id ){
	$.ajax({
		url:'${ctxPath}/RoomType/delRoomType',
		type:'post',
		data:{id:_id},
		dataType:'json',
		success:function( resp ){
			var result = resp['result'];
			//{ps} 关闭弹窗
			layer.closeAll();
			if(result=='success'){
				layer.msg('删除房间：'+_id+'成功',{icon:1,time:2000,offset:'20px'});
				//{1} 1.0秒重新刷新页面。
				setTimeout( reloadPage, 1000 );
			}else{
				layer.msg('删除房间:'+_id+'失败, 原因:'+ resp['cause'],{icon:2,time:2000,offset:'20px'});
			}
		}
	});
}

$(document).on('mouseenter', 'div.layui-card-body > form > div:nth-child(1) > div > div.layui-form-mid.layui-word-aux', function () {
	if($(this)[0].innerHTML.indexOf("只读")>=0)
   	layer.tips("只可选中复制，不可修改", this, {tips: [2, '#5FB878'], time: 1000});
})

$(document).on('mouseenter', '#LAY_layuipro > div > div > div.layui-card-header', function () {
    var data = $(this).attr('lay-value');
   	layer.tips("id:"+data, this, {tips: [1, '#5FB878'], time: 2000});
})


</script>

</body>
</html>        

